import { openDB } from 'idb'
import type { conversation } from '@/api/messages/type'

// //封装本地存储数据与读取数据的方法
// export const SET_CHAT = (chatHistory: conversation[]) => {
//     localStorage.setItem('CHAT', JSON.stringify(chatHistory))
// }

// export const GET_CHAT = () => {
//     const localChat = localStorage.getItem('CHAT')
//     // 检查存储的值是否存在，然后将其解析为对象
//     return localChat ? JSON.parse(localChat) : []
// }

// export const REMOVE_CHAT = () => {
//     localStorage.removeItem('CHAT')
// }

//封装本地存储数据与读取数据的方法
export const SET_CHAT = async (chatHistory: conversation[]) => {
    const db = await openDB('directoryDB', 2, {
        upgrade(db) {
            //确保'directories'对象存储已经被创建
            if (!db.objectStoreNames.contains('directories')) {
                db.createObjectStore('directories')
            }
        },
    })
    await db.put('directories', chatHistory, 'CONVERSATIONS')
}

export const GET_CHAT = async () => {
    const db = await openDB('directoryDB', 2, {
        upgrade(db) {
            //确保对象仓库已经存在
            if (!db.objectStoreNames.contains('directories')) {
                db.createObjectStore('directories')
            }
        },
    })
    const conversations = await db.get('directories', 'CONVERSATIONS')
    return conversations || []
}

export const REMOVE_CHAT = async () => {
    const db = await openDB('directoryDB', 2, {
        upgrade(db) {
            //确保对象仓库已经存在
            if (!db.objectStoreNames.contains('directories')) {
                db.createObjectStore('directories')
            }
        },
    })
    await db.delete('directories', 'CONVERSATIONS')
}
